package com.cyzy.config;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.cyzy.dto.RequestDTO;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class Sentinelconfig {
    //流量控制
    private void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        //秒杀流量控制

        FlowRule signInRule = new FlowRule("signIn")
                .setGrade(RuleConstant.FLOW_GRADE_QPS)//QPS
                .setCount(20)
                .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT)//快速失败
                .setClusterMode(false);//单机模式
        rules.add(signInRule);
        FlowRuleManager.loadRules(rules);

    }
    private void initDegradeRules(){
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule signInRule = new DegradeRule("signIn")
                .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO)//RT
                .setCount(0.5)
                .setTimeWindow(10)
                .setMinRequestAmount(20)
                .setStatIntervalMs(1000);
        rules.add(signInRule);
        DegradeRuleManager.loadRules(rules);
    }

    @PostConstruct
    public void init(){
        initFlowRules();
        initDegradeRules();
    }

    //流控后友好提示
    public static RequestDTO handBlock(MultipartFile image,
                                       String userId,
                                       String liveName, BlockException ex){
        return new RequestDTO(400,"请稍后再试！",null);
    }

    public static RequestDTO handFallBlock( String image,
                                    String userId,
                                    String liveName,Throwable t){
        return new RequestDTO(400,"请稍后再试！",null);
    }
}
